package com.edu.hre.db.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;



import com.edu.hre.common.CurrentUserInfo;
import com.edu.hre.db.config.BaseDAO;
import com.edu.hre.db.config.DBPool;
import com.edu.hre.db.dto.HreEmpBasicsalary;
import com.edu.hre.db.dto.HreEmpEducation;
import com.edu.hre.db.dto.HreEmpEmergencyContact;
import com.edu.hre.db.dto.HreEmpDependent;
import com.edu.hre.db.dto.HreEmpWorkExperience;


public class LoginDAO  extends BaseDAO {
	private static final Logger logger = Logger.getLogger(LoginDAO.class);
	public CurrentUserInfo ValidateLogin(String username, String password) {
		Connection conn = null;
		PreparedStatement preStmt = null;
		ResultSet rs = null;
		CurrentUserInfo userInfo = new CurrentUserInfo();
		try {
			conn = DBPool.getConnection();
			String strSQLQuery = "SELECT * FROM hre_user u "
					+ " JOIN hre_employee e ON u.emp_number = e.emp_number"
					+ " JOIN hre_user_role_screen rs ON rs.user_role_id = u.user_role_id"
					+ " WHERE u.user_name = '"
					+ username
					+"' AND u.user_password = '"
					+ password
					+ "' AND u.deleted = 0";
			preStmt = conn.prepareStatement(strSQLQuery);
			rs = preStmt.executeQuery();
			if (rs.next()){
				userInfo.setValid(true);
				userInfo.setUserId(rs.getInt("emp_number"));
				userInfo.setUserShortName(rs.getString("emp_firstname"));
				userInfo.setUserRoleId(rs.getInt("user_role_id"));
				userInfo.setUserSubUnitId(rs.getInt("work_station"));
				userInfo.setUserIdSurvey(rs.getInt("id"));
			}
			else userInfo.setValid(false);
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		} finally {
			// đóng PreparedStatement, ResultSet và đẩy connection vào pool
			releaseConnection(conn, preStmt, rs);
		}
		
		try {
			conn = DBPool.getConnection();
			String strSQLQuery = "SELECT * FROM hre_user_role_screen "
					
					+ " WHERE user_role_id = "
					+ userInfo.getUserRoleId()
					+" AND action_name IN( \'employeeList\',\'dashResource\',\'dashLeave\')";
			preStmt = conn.prepareStatement(strSQLQuery);
			rs = preStmt.executeQuery();
			while (rs.next()){
				String actionName = rs.getString("action_name");
				boolean canView = rs.getBoolean("can_read");
				if (actionName.equals("employeeList"))
					userInfo.setCanViewEmployee(canView);
				else if (actionName.equals("dashResource"))
					userInfo.setCanViewChartResouce(canView);
				else if (actionName.equals("dashLeave"))
					userInfo.setCanViewChartLeave(canView);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		} finally {
			// đóng PreparedStatement, ResultSet và đẩy connection vào pool
			releaseConnection(conn, preStmt, rs);
		}
		return userInfo;

	}

}
